const app = getApp(); //引入导航
var util = require('../../utils/common.js'); //引入公共JS
var WSCoordinate = require('../../utils/WSCoordinate.js'); //引入坐标系转换
var fsm = tt.getFileSystemManager();
var FILE_BASE_NAME = 'tmp_base64src';
var Small_program_code = '';
import { Ycdetail } from 'ycdetail_model.js';
var ycdetail = new Ycdetail();
var wxParse = require('../../wxParse/wxParse.js'); //引入

var id = '';
var title = '';
var typeid = '';
Page({
  data: {
    showIcon: true,
    //显示返回键以及首页
    showMessage: false,
    //点击弹出的缺货登记提示显示
    SaleFlag: true,
    //缺货登记
    DaiDing: true,
    stockFlag: true,
    //缺货登记
    selectData: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
    //下拉列表的数据
    topFlag: false,
    seatFlag: true,
    // 座位图
    scrollTop: 0,
    // 页面滚动，返回顶部
    id: null,
    kfFlag: true,
    // 底部客服
    noLogin: false,//未登录
    code: "E7AI98",
    litpic: '',
    qr_code: '',
    maskHidden: false,
    kefuphoneArr: []
  },
  onLoad: function (options) {
    // 显示分享展示按钮
    tt.showShareMenu({
      success(res) {
        console.log("已成功显示转发按钮");
      },
      fail(err) {
        console.log("showShareMenu 调用失败", err.errMsg);
      },
      complete(res) {
        console.log("showShareMenu 调用完成");
      },
    });

    console.log(options)
    var source = options.source;

    if (source) {
      tt.setStorageSync('source', source);
    }

    var scene = options.scene;

    if (scene) {
      var arr = scene.split("%2C");

      if (arr.length == 2) {
        scene = arr[0];
        this.data.mMid = arr[1];
      } else {
        scene = arr[0];
      }

      tt.setStorageSync('mMid', this.data.mMid);
    } else {
      scene = '';
      tt.setStorageSync('mMid', '');
    }

    const userinfo = tt.getStorageSync('userInfo');

    if (userinfo) {
      var kefu = [{
        'name': JSON.parse(userinfo).nickName,
        'url': JSON.parse(userinfo).avatarUrl,
        'come': '小程序'
      }];
      var kefupara = JSON.stringify(kefu[0]);
      this.setData({
        kefupara: kefupara
      });
    }

    if (scene) {
      id = scene;
    } else {
      id = options.id; //项目id
    }

    this.data.id = id;

    this._loadDate();

    kfFlag: options.kfFlag == "true" ? true : false; //客服
    //页面打开判断是否登陆过

    ycdetail.getJQListArr(this.data.id, res => {
      this.setData({
        'getJQListArr': res
      });
    }); 
    
    // 获取客服手机号
    let kefuphone = tt.getStorageSync('kefuphoneArr');
    if (!kefuphone) {
      util.kefuphone();
    }
    this.setData({
      kefuphoneArr: kefuphone.slice(0, 2)
    });
  },
  //跳转页面时关闭客服弹框
  onHide: function () {
    this.setData({
      kfFlag: true
    });
  },
  //座位图
  seatShow: function () {
    this.setData({
      seatFlag: false
    });
  },
  //关闭座位图
  seatHide: function () {
    this.setData({
      seatFlag: true
    });
  },
  // 获取滚动条当前位置
  onPageScroll: function (e) {
    if (e.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },
  //地图导航
  getmap: function (e) {
    var mpcoordinate = e.target.dataset.mpcoordinate;
    var shorttitle = e.target.dataset.shorttitle;
    var venue = e.target.dataset.venue;
    var a = mpcoordinate.split(",");
    var latitude = a[1] * 1;
    var longitude = a[0] * 1;
    var result3 = WSCoordinate.transformFromBaiduToGCJ(latitude, longitude);
    latitude = result3.latitude;
    longitude = result3.longitude;
    tt.openLocation({
      latitude: latitude,
      longitude: longitude,
      scale: 18,
      name: shorttitle,
      address: venue
    });
  },
  //回到顶部
  goTop: function () {
    util.goTop();
  },
  _loadDate: function () {
    ycdetail.getDetailfint(this.data.id, data => {
      console.log(11, data); // 演出详情

      wxParse.wxParse('article', 'html', data.body, this, 5); // 基本信息

      if (data['jbxx'] == '') {
        this.setData({
          jbxx: 1
        });
      } else {
        wxParse.wxParse('articlez', 'html', data['jbxx'], this, 5);
        this.setData({
          jbxx: data['jbxx']
        });
      } // 场馆


      if (typeof data.venue == 'object') {
        this.setData({
          'changguan': data.venue
        });
      } else {
        this.setData({
          'changguan': -2
        });
      } // 城市


      var chengshi = data.chengshi;
      var data1 = chengshi.replace('市', '');
      var data2 = data1.replace('省', '');
      this.setData({
        'name': data2
      });
      title = data.shorttitle;
      this.data.title = title;
      typeid = data.typeid;
      this.data.typeid = typeid;
      var clickNum = data.click; //获取点击量

      console.log(data.shorttitle + "的id为" + data.id); //打印当前票品的ID值（不要屏蔽）

      var _tum, _num;

      if (clickNum <= 30) {
        _tum = 10 + "%", _num = '1.0';
      } else if (30 < clickNum && clickNum < 50) {
        _tum = 20 + "%", _num = '2.0';
      } else if (50 <= clickNum && clickNum < 100) {
        _tum = 30 + "%", _num = '3.0';
      } else if (100 <= clickNum && clickNum < 200) {
        _tum = 40 + "%", _num = '4.0';
      } else if (200 <= clickNum && clickNum < 300) {
        _tum = 50 + "%", _num = '5.0';
      } else if (300 <= clickNum && clickNum < 1000) {
        _tum = 60 + "%", _num = '6.0';
      } else if (1000 <= clickNum && clickNum < 3000) {
        _tum = 70 + "%", _num = '7.0';
      } else if (3000 <= clickNum && clickNum < 10000) {
        _tum = 80 + "%", _num = '8.0';
      } else if (10000 <= clickNum && clickNum < 30000) {
        _tum = 90 + "%", _num = '9.0';
      } else if (clickNum >= 30000) {
        _tum = 100 + "%", _num = '10';
      } //评星级

      this.setData({
        "percenTum": "" + _tum + "",
        "percenTge": _num
      });
      wxParse.wxParse('articlex', 'html', data.gpxz, this, 5); //....

      this.setData({
        'product': data
      });
      this.data.litpic = data.litpic;
    });

    ycdetail.getYanZheng(this.data.id, data => {
      if (data >= 0) {
        this.setData({
          isCollect: true //点击授权的时候收藏成功！
        });
      }
    }); 
    // ycdetail.getQnums(this.data.id, (data) => { //问答数量
    //   this.setData({
    //     'getQnums': data
    //   });
    // });

    ycdetail.getProject(this.data.id, data => {
      //演出详情票列表
      this.setData({
        'getProject': data
      }); // 热门演出推荐不够6个运行一下内容

      if (data.length < 6) {
        ycdetail.getProjeArr(this.data.id, data => {
          this.setData({
            'getProjeArr': data
          });
        });
      }
    });
  },
  selectTap: function (e) {
    // 点击下拉显示框
    this.setData({
      show: !this.data.show
    });
  },
  optionTap: function (e) {
    // 点击下拉列表
    var Index = e.currentTarget.dataset.index; //获取点击的下拉列表的下标

    this.setData({
      index: Index,
      show: !this.data.show
    });
  },
  // 底部客服点开显示隐藏效果
  kfChange: function () {
    var that = this;
    that.setData({
      kfFlag: !that.data.kfFlag
    });
  },
  kfHide: function () {
    this.setData({
      kfFlag: true
    });
  },
  // 底部拨打电话
  calling: function () {
    util.calling();
  },
  //生成海报并保存到本地
  ewmOpen: function () {
    //获取二维码并显示背景图片
    var _page = "pages/ycdetail/ycdetail";
    console.log(id);
    ycdetail.get_qr_code(id, this.data.mMid, _page, res => {
      console.log(res)
      this.setData({
        qr_code: res,
        CodeFlag: false,
        maskHidden: false
      });
      tt.showToast({
        title: '海报生成中...',
        icon: 'loading',
        duration: 2000
      });
      var that = this;
      setTimeout(function () {
        tt.hideToast();
        that.createNewImg();
        that.setData({
          maskHidden: true
        });
      }, 1000);
    });
  },
  //画图
  createNewImg: function () {
    var that = this;
    var path1 = "../../image/fx2.jpg";
    var path2 = that.data.litpic; //项目图片

    if (!/^https/.test(path2)) {
      path2 = path2.replace(/^http/, "https");
    }

    var path3 = that.data.qr_code; //二维码

    // path3 = that.base64src(path3);
    // path3 = Small_program_code;
    console.log(path3); 
    
    //将模板图片绘制到canvas,在开发工具中drawImage()函数有问题，不显示图片
    var context = tt.createCanvasContext('mycanvas');
    context.setFillStyle("#ffe200");
    context.fillRect(0, 0, 375, 667);
    tt.downloadFile({
      url: path2,
      success: function (res) {
        path2 = res.tempFilePath;
        console.log('临时文件地址是path2：' + res.tempFilePath); //绘制图片

        context.drawImage(path1, 0, 0, 375, 667);
        context.drawImage(path2, 51.5, 51.5, 272, 366);
        context.drawImage(path3, 51.5, 480, 95, 95);
        context.save();
        context.setFontSize(18);
        context.setFillStyle('#fff');
        context.fillText("大河票务", 160, 510);
        context.setFontSize(12);
        context.fillText("演出门票", 160, 560);
        context.setFontSize(12);
        context.fillText("旅游景点", 220, 560);
        context.setFontSize(12);
        context.fillText("本地吃喝", 280, 560);
        context.stroke();
        context.setFontSize(14);
        context.setTextAlign('center');
        context.fillText("大河票务网，为您的品质生活而来！", 188, 640);
        context.stroke();
        context.draw(); //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时

        setTimeout(function () {
          tt.canvasToTempFilePath({
            canvasId: 'mycanvas',
            success: function (res) {
              var tempFilePath = res.tempFilePath;
              console.log(tempFilePath);
              tt.saveImageToPhotosAlbum({
                filePath: tempFilePath,

                success(res) {
                  console.log("success");
                },

                fail: function (res) {
                  console.log(res);
                }
              });
              that.setData({
                imagePath: tempFilePath,
                canvasHidden: true
              });
            },
            fail: function (res) {
              console.log(res);
            }
          });
        }, 200);
        console.log('小程序码地址：' + path3);
      }
    });
  },
  //base64字符串转图片
  base64src: function (base64data) {
    return new Promise((resolve, reject) => {
      const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];

      if (!format) {
        reject(new Error('ERROR_BASE64SRC_PARSE'));
      }

      var id = this.data.id;
      var filePath = `${tt.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${id}.${format}`;
      Small_program_code = filePath;
      const buffer = tt.base64ToArrayBuffer(bodyData);
      fsm.writeFile({
        filePath,
        data: buffer,
        encoding: 'binary',

        success() {
          resolve(filePath);
        },

        fail() {
          reject(new Error('ERROR_BASE64SRC_WRITE'));
        }

      });
    });
  },
  //关闭蒙版，和海报
  imagePathBox: function () {
    this.setData({
      maskHidden: false
    });
  },
  //点击分享
  onShareAppMessage: function () {
    util.sharePage();
  },
  //打开开售登记
  SaleShow: function () {
    this.setData({
      SaleFlag: false,
      DaiDing: true
    });
  },
  //关闭开售登记
  SaleHide: function () {
    this.setData({
      SaleFlag: true,
      DaiDing: true
    });
  },
  //项目待定登记
  DaiDingShow: function () {
    this.setData({
      DaiDing: false,
      SaleFlag: true
    });
  },
  //项目待定登记
  XiangMuHide: function () {
    this.setData({
      DaiDing: true,
      SaleFlag: true
    });
  },
  KnameInput: function (e) {
    //监听姓名输入
    this.data.Dname = e.detail.value;
  },
  KphoneInput: function (e) {
    //监听手机号输入
    this.data.Dphone = e.detail.value;
  },
  KwordInput: function (e) {
    //监听留言输入
    this.data.Dword = e.detail.value;
  },
  //提交项目待定登记
  SaleRefer: function () {
    var nameRule = /^[\u2E80-\u9FFF]+$/,
        telRule = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[1|3|5|8|9])[0-9]{8}$/; //验证手机号
    var Dname = this.data.Dname; //姓名
    var Dphone = this.data.Dphone; //手机号
    var Dword = this.data.Dword; //留言
    if (Dname == undefined || Dname == "") {
      this.showMessage('请输入姓名');
    } else if (!nameRule.test(Dname)) {
      this.showMessage('请输入有效字符');
    } else if (Dphone == undefined || Dphone == "") {
      this.showMessage('手机号不能为空');
    } else if (!telRule.test(Dphone)) {
      this.showMessage('手机号格式不正确');
    } else if (Dword == undefined || Dword == "") {
      this.showMessage('请添加备注');
    } else {
      var products = {
        "aid": id,
        "name": Dname,
        "phone": Dphone,
        "word": Dword
      };
      ycdetail.getDaiDengJi(products, data => {
        this.setData({
          //关闭提交登记
          DaiDing: true
        });

        if (data == 1) {
          tt.showToast({
            title: '提交登记成功！'
          });
        } else {
          tt.showToast({
            title: '无需重复提交'
          });
        }
      });
    }
  },
  //开售登记
  phoneInput: function (e) {
    //监听手机号输入
    this.data.phone = e.detail.value;
  },
  wordInput: function (e) {
    //监听留言输入
    this.data.word = e.detail.value;
  },
  stockRefer: function () {
    var _index = this.data.index; //点击数量的下标
    var _phone = this.data.phone; //手机号
    var _num = this.data.selectData[_index]; //下拉选择的数量
    var _word = this.data.word; //留言
    var telRule = /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[1|3|5|8|9])[0-9]{8}$/; //验证手机号
    console.log(_phone, _num, _word);
    if (_phone == "" || _phone == undefined) {
      this.showMessage('手机号不能为空');
    } else if (!telRule.test(_phone)) {
      this.showMessage('手机号格式不正确');
    } else if (_num == "" || _num == undefined) {
      this.showMessage('数量不能为空');
    } else if (_word == "" || _word == undefined) {
      this.showMessage('请备注信息');
    } else {
      var products = {
        "aid": id,
        "phone": _phone,
        "num": _num,
        "ycid": '0',
        "qyid": '0',
        "word": _word
      };
      ycdetail.getKaiShou(products, data => {
        this.setData({
          //关闭提交登记
          SaleFlag: true
        });

        if (data == 1) {
          tt.showToast({
            title: '提交登记成功！'
          });
        } else {
          tt.showToast({
            title: '无需重复提交'
          });
        }
      });
    }
  },
  stockHide: function (e) {
    // 关闭缺货登记
    this.setData({
      stockFlag: true
    });
  },
  stockShow: function (e) {
    // 关闭缺货登记
    this.setData({
      stockFlag: false
    });
  },
  showMessage: function (text) {
    //打开提示弹框
    var that = this;
    that.setData({
      showMessage: true,
      messageContent: text
    });
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      });
    }, 3000);
  },
  //小程序判断是否收藏
  haveSave: function () {
    var _isCollect = this.data.isCollect; 
    //获取当前时间戳
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var aid = id;
    var title1 = title;
    var addtime = timestamp;
    var typeid1 = typeid;
    ycdetail.getShouCang(aid, title1, addtime, typeid1, res => {
      console.log(res);
      if (res == 1) {
        this.setData({
          isCollect: true //点击授权的时候收藏成功！
        });
        tt.showToast({
          title: '已收藏'
        });
        setTimeout(function () {
          tt.hideToast();
        }, 1000);
      } else {
        this.setData({
          isCollect: true //点击授权的时候收藏成功！
        });
        tt.showToast({
          title: '收藏过了！'
        });
        setTimeout(function () {
          tt.hideToast();
        }, 1000);
      }
    });
  },
  
  previewImage: function (e) {
    this.setData({
      seatFlag: true
    });
    var index = e.currentTarget.dataset.index;
    var pictures1 = this.data.pictures;
    var pictures = new Array();
    pictures[0] = index;
    tt.previewImage({
      current: pictures[0],
      urls: pictures
    });
  },
  // 判断是否登录
  islogin(){
    const token=tt.getStorageSync('token');
    const url = '/pages/ycSelect/ycSelect?aid='+this.data.product.id+'&title='+this.data.product.shorttitle+'&z=DY'
    console.log(url)
    if(token == ''){
      util.login(url)
    }else{
      tt.navigateTo({
        url: url // 指定页面的url
      });
    }
  }
});